# -*-coding:utf-8 -*-
from utils import logs
__author__ = 'Junn'

from django.db.models import Manager, Q
from django.db import connection


def execute_raw_sql(sql):
    """
    @param sql:需要执行的sql语句
    @summary: 对自定义的sql语句进行执行
    """
    data_cursor = connection.cursor()
    data_cursor.execute(sql)


class BaseManager(Manager):
    def __init__(self):
        super(BaseManager, self).__init__()

    def query_for_list(self, sql, meta=None, args=None):
        """
        @param sql:查询的sql语句
        @param meta:需要进行映射的map的key(必须和sql语句中的字段顺序一致)
        @return: 返回的data中的每一项为map
        """
        data_cursor = connection.cursor()
        if args:
            data_cursor.execute(sql, args)
        else:
            data_cursor.execute(sql)
        data = []
        result = data_cursor.fetchall()
        if result:
            if isinstance(meta, dict):
                keys = meta.keys()

                for row in result:
                    row_map = {}
                    i = 0
                    for key in keys:
                        row_map[meta[key]] = unicode(row[i])
                        i += 1
                    data.append(row_map)
            elif isinstance(meta, (list, tuple)):
                for row in result:
                    row_map = {}
                    i = 0
                    for key in meta:
                        row_map[key] = unicode(row[i]) if row[i] != None else ''
                        i += 1
                    data.append(row_map)
            else:
                data = result
        return data

    def execute_sql(self, sql):
        """
        @param sql:需要执行的sql语句
        @summary: 对自定义的sql语句进行执行
        """
        execute_raw_sql(sql)

    def get_by_id(self, id, q=None):
        q = q & Q(id=id) if q else Q(id=id)
        try:
            return self.get(q)
        except Exception, e:
            logs.error('' + e)
            return None

    def get_obj(self, q):
        try:
            return self.get(q)
        except Exception, e:
            logs.error('' + e)
            return self.filter(q)[0] if self.filter(q) else None

